import { searchGoods } from '@src/api/mall/search'
import mall from '@src/store/mall'
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { getStoreMenu, getStoreGoodsList, getDispatchWay, getStoreDetail  } from '@src/api/mall/store'
import { addGoodsToCart, getCartGoods, updateCartGoods, batchDeleteItem } from '@src/api/mall/storeCart'
import { preOrderFun } from '@src/api/mall/order'
import router from "@src/router";
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: mall,
      fields: ['storeId']
    }
  ],

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    title: '搜索',
    key: '',
    skuShow: false,
    isFocus: false,
    timer: null,
    pageNum: 1,
    goodsList: [],
    lock: false,
    fileBaseUrl: null,
    history: [],
    items: [], 
    priceCount: 0,
    menuIdList: [],
    // 当前选中商品
    goodsSelected: {},
    // skuId
    skuSelectedIds: [],
    // 筛选出来的sku
    selectedSkuData: {},
    cartList: [],
    items: [],
    cartIds: [],
    source: 0,
    storeInfo: {},
    nowBuyItem: [],
    isRequest: false,
    isOpenDispatch: true,
    cartAddForm: {
      cartType: 0,
      children: [],
      goodsId: null,
      num: 1,
      remark: null,
      skuId: null,
      storeId: null,
      type: 'NO_CHOICE'
    },
    deliveryType: '',
    cartNum: 0,
    dispatchWayDescribe: [
      {
        title: '外卖配送',
        describe: '支持配送',
        image: '../../../static/icon/take_out.png',
        status: 2,
        str: 'LOCAL',
        disabled: false,
        isShow: false,
        goods: []
      },
      {
        title: '到店自提',
        describe: '支持自提',
        image: '../../../static/icon/store.png',
        status: 2,
        str: 'SELF_PICKUP',
        disabled: false,
        isShow: false,
        goods: []
      },
      {
        title: '快递邮寄',
        describe: '支持邮寄',
        image: '../../../static/icon/fast_mail.png',
        status: 2,
        str: 'EXPRESS',
        disabled: false,
        isShow: false,
        goods: []
      }
    ]
  },
  observers: {
    'storeId'(storeId) {
      console.log(storeId)
      if(storeId) {
        this.getCartGoods()
        this.getStoreInfo()
      }
    }
  },
  methods: {
    onLoad(query) {
      let { menuIdList } = query 
      if(!menuIdList) {wx.navigateBack()}
      this.setData({menuIdList: menuIdList.split(',')})
      this.setData({
        fileBaseUrl: getApp().globalData.extConfig.fileBaseUrl
      })
      if(!wx.getStorageSync('history')) {
        wx.setStorageSync('history', JSON.stringify([]))
      }else {
        this.setData({history:JSON.parse(wx.getStorageSync('history'))})
      }
      
    },
    bindscrolltolower() {
      this.fetchData()
    },
    toCart() {
      router.push({
        name: 'mall/store-cart'
      })

    },
    previewImage({target}) {
      const { urls } = target.dataset
      let images = []
      urls.forEach(item => {images.push(this.data.fileBaseUrl + item)})
      wx.previewImage({
        urls: images
      })
    },
    dispatchHide() {
      this.setData({dispatchShow:false})
    },
    getStoreInfo() {
      getStoreDetail({storeId: this.data.storeId})
      .then(res => {
        const {  supplyLocal, supplySelfPickup, supplyExpress } = res.data.delivery
        if(!supplyLocal && !supplySelfPickup && !supplyExpress) {
          this.setData({isOpenDispatch: false, storeInfo: res.data})
          return
        }
        let dispatchWayDescribe = this.data.dispatchWayDescribe
        dispatchWayDescribe[0].isShow = false
        dispatchWayDescribe[1].isShow = false
        dispatchWayDescribe[2].isShow = false
        supplyLocal && (dispatchWayDescribe[0].isShow = true)
        supplySelfPickup && (dispatchWayDescribe[1].isShow = true)
        supplyExpress && (dispatchWayDescribe[2].isShow = true)
        this.setData({dispatchWayDescribe, storeInfo: res.data})
      })
    },
    getDispatchWay() {
      const { supplyExpress, supplyLocal, supplySelfPickup } = this.data.storeInfo.delivery
      const { source, items } = this.data
      if(!supplyExpress && !supplyLocal && !supplySelfPickup) {
        wx.showToast({
          title: '当前门店未配置任何配送方式，暂时无法下单',
          icon: 'none'
        })
        return
      }
      if(source == 0 && !items.length) return
      
      let params = {
        items: (this.data.source == 0 ? this.data.items : this.data.nowBuyItem),
        storeId: this.data.cartList[0].storeId,
        subType: '',
        source: this.data.source
      }
      getDispatchWay(params)
      .then(res => {
        if(res.code !== 0) return
        this.setData({dispatchShow: true})
        let dispatchWayDescribe = this.data.dispatchWayDescribe
        const { 
          supplyExpress, 
          expressItems,
          localItems,
          selfPickupItems,
          supplyLocal, 
          supplySelfPickup
        } = res.data
        dispatchWayDescribe[0].disabled = !!!supplyLocal
        dispatchWayDescribe[0].status = supplyLocal
        dispatchWayDescribe[0].goods = localItems
        dispatchWayDescribe[1].disabled = !!!supplySelfPickup
        dispatchWayDescribe[1].status = supplySelfPickup
        dispatchWayDescribe[1].goods = selfPickupItems
        dispatchWayDescribe[2].disabled = !!!supplyExpress
        dispatchWayDescribe[2].status = supplyExpress
        dispatchWayDescribe[2].goods = expressItems
        this.setData({dispatchWayDescribe})
      })
      
    },
    historyChange({target}) {
      const { key } = target.dataset
      this.setData({key})
      this.fetchData()
    },
    selectedDispatchWay({ currentTarget }) {
      const { dispatch } = currentTarget.dataset
      console.log(dispatch)
      if(dispatch.disabled) return
      this.setData({deliveryType: dispatch.str})
      this.handlePreOrder(dispatch.goods)
    },
    handlePreOrder(goods = []) {
      let selectCartList = (this.data.source == 0 ? goods : this.data.nowBuyItem)
      if (this.data.source == 0 && selectCartList.length === 0) {
        return;
      }

      let orderPreForm = {
        items: [],
        source: this.data.source,
        storeId: this.data.storeId,
        type: this.data.deliveryType
      };
      console.info()
      selectCartList.forEach(item => {
        orderPreForm.items.push(item)
      })
      wx.showLoading({title: "下单中...", mark: true});
      let deliveryType = this.data.deliveryType
      preOrderFun(orderPreForm).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          this.setData({dispatchShow: false, source: 0})
          router.push({
            name: 'mall/submit-order',
            params: {
              preNo: res.data.preNo, 
              deliveryType: deliveryType, 
              storeNo: this.data.storeInfo.storeNo
            },
            success: (res) => {
              if (deliveryType === 'LOCAL') {
                setTimeout(() => {
                  res.eventChannel.emit('showSelectDelivery');
                }, 300)
              }
            }
          })
        }
      }).catch((res)=>{
        this.setData({dispatchShow: false, source: 0})
        if(res.data.data.invalidItems.length>0){
          wx.showToast({
            icon: 'none',
            title:res.data.data.invalidItems[0].title+res.data.data.invalidItems[0].errorMsg,
          })
        }
      })
    },
    openSku({ target }) {
      const { goodinfo } = target.dataset
      console.log(goodinfo)
      const { skuList, specList } = goodinfo.skuInfo
      this.setData({ skuShow: true, goodsSelected: goodinfo })
      //打开窗口自动选择第一个sku
      if (!this.data.skuSelectedIds.length) {
        let skuSelectedIds = skuList[0].specAttrs.slice(0, specList.length)
        this.setData({ skuSelectedIds, selectedSkuData: skuList[0] })
      }

    },
    async addBtn(e) {
      const { goodinfo, isadd, count } = e.target.dataset
      const { skuInfo } = goodinfo
      const { items } = this.data
      if(skuInfo.skuList.length <= 1 && skuInfo.skuList[0].stockNum <= 0) {
        wx.showToast({
          title: '已售罄',
          icon: 'none'
        })
        return
      }
      //有多sku
      if (skuInfo.skuList.length > 1) {
        const filterGoods = items.filter(item => goodinfo.goodId === item.goodsId)
        if(!isadd && filterGoods.length <= 1 && filterGoods[0].num > 1) {
          let { cartItemId,storeId,num, goodsId, skuId } = filterGoods[0]
          let params = {
            cartItemId,
            storeId,
            num: --num,
            goodsId,
            skuId
          }
          await updateCartGoods(params)
          this.getCartGoods()

          return
        } else if(!isadd && filterGoods.length > 1) {
          wx.showToast({
            title: '请到购物车减购',
            icon: 'none'
          })
          return
        } else if(!isadd && filterGoods.length <= 1 && filterGoods[0].num <= 1) {
          let { cartItemId,storeId} = filterGoods[0]
          batchDeleteItem([{cartItemId, storeId}]).then(res => {
            this.getCartGoods()
          })
          return
        }

        
        this.openSku(e)
        return
      }
      this.setData({ goodsSelected: goodinfo, selectedSkuData: goodinfo.skuInfo.skuList[0] })
      //单个sku
      if (isadd) {
        this.addCart()
      } else if (!isadd && count > 1) {
        const filter = this.data.items.filter(item => item.goodsId === goodinfo.goodId)[0]
        console.log(filter)
        let { cartItemId,storeId,num, goodsId, skuId } = filter
        let params = {
          cartItemId,
          storeId,
          num: --num,
          goodsId,
          skuId
        }
        await updateCartGoods(params)
        this.getCartGoods()
      } else if(!isadd && count <= 1) {
        const filter = this.data.items.filter(item => item.goodsId === goodinfo.goodId)[0]
        let { cartItemId,storeId } = filter
        batchDeleteItem([{cartItemId, storeId}]).then(res => {
          this.getCartGoods()
        })
      }
    },
    //添加购物车
    addCart() {
      const { goodId } = this.data.goodsSelected
      const cartAddForm = this.data.cartAddForm
      cartAddForm.storeId = this.data.storeId
      cartAddForm.goodsId = goodId
      cartAddForm.skuId = this.data.selectedSkuData.skuId
      addGoodsToCart(cartAddForm)
        .then(res => {
          wx.showToast({
            title: '宝贝已添加到购物车',
            icon: 'none',
            duration: 1000
          })
          this.initCartChange()
        })

    },
     //初始化购物车函数
     initCartChange() {
      const cartAddForm = {
        cartType: 0,
        children: [],
        goodsId: null,
        num: 1,
        remark: null,
        skuId: null,
        storeId: null,
        type: 'NO_CHOICE'
      }
      this.setData({
        cartAddForm,
        skuShow: false
      })
      this.getCartGoods()
    },
    clearKey() {
      this.setData({key: '', isRequest: false, goodsList: [], lock: false})
    },
    clearHistory() {
      this.setData({history: []})
      wx.setStorageSync('history', JSON.stringify([]))
    },
    saveHistory() {
      let history = this.data.history
      let key = this.data.key.trim()
      if(!key) return
      history.unshift(key)
      history = [...new Set(history)]
      this.setData({history})
      wx.setStorageSync('history', JSON.stringify(history))
    },
    // 计算count
    countChange({ target }) {
      const { isadd } = target.dataset
      const { num } = this.data.cartAddForm
      const cartAddForm = this.data.cartAddForm
      if (isadd) {
        cartAddForm.num += 1
      } else if (!isadd && num > 1) {
        cartAddForm.num -= 1
      }
      this.setData({ cartAddForm })
    },
    popSkuChange({ target }) {
      const { index, id } = target.dataset
      const { skuList, specList } = this.data.goodsSelected.skuInfo
      const ids = this.data.skuSelectedIds
      ids[index] = id
      this.setData({ skuSelectedIds: ids })
      let selectedSkuData = skuList.filter((item) => {
        let specAttr = item.specAttrs.slice(0, specList.length)
        return JSON.stringify(specAttr) === JSON.stringify(ids)
      })?.[0]

      if (!selectedSkuData) {
        return
      }
      console.log(selectedSkuData)
      this.setData({ selectedSkuData })
    },
    throttleSearch(fn) {
      clearTimeout(this.data.timer)
      let timer = setTimeout(() => {
        this.saveHistory()
        fn && fn()
        this.setData({ timer: null })
      }, 1000)
      this.setData({ timer })
    },
    inputKeyChange() {
      this.setData({isRequest: false, pageNum: 1, lock: false, goodsList: []})
      this.throttleSearch(this.fetchData.bind(this))
    },
    fetchData() {
      const { key, pageNum, storeId, menuIdList, lock  } = this.data
      if(lock || !key.trim()) return
      searchGoods({
        name: key,
        pageNum,
        pageSize: 10,
        storeId,
        menuIdList
      })
        .then(res => {

          if(res.data.list.length >= 10) {
            this.setData({pageNum: ++this.data.pageNum})
          }else {
            this.setData({lock: true})
          }
          this.setData({isRequest: true, goodsList: [...this.data.goodsList, ...res.data.list]})
        })
    }, 
    buyNow() {
      let item = {
        goodsId: this.data.goodsSelected.goodId,
        num: this.data.cartAddForm.num,
        price: this.data.selectedSkuData.price,
        skuId: this.data.selectedSkuData.skuId,
        storeId: this.data.storeId
      }
      this.setData({source: 1, skuShow: false, nowBuyItem: [item] })
      this.getDispatchWay()
      
    },
    getCartGoods() {
      getCartGoods({ cartType: 0, storeId: this.data.storeId, type: 'NO_CHOICE' })
        .then(res => {
          this.setData({ cartList: res.data })
          let cartList = []
          let cartNum = 0
          let map = res.data.map(item => item.items)
          map.forEach(item => { cartList.push(...item) })
          let priceCount = cartList.reduce((prev, cur) => prev + (cur.price * cur.num), 0)
          const cartIds = cartList.map(item => item.goodsId)
          cartList.forEach(item => {cartNum += item.num})
          this.setData({ items: cartList, priceCount, cartIds, cartNum })
        })
    },
    changeBlur() {
      this.setData({ isFocus: false })
    },
    changeFocus() {
      this.setData({ isFocus: true })
    }
  }

})
